package main

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"path"
	"time"
)

func main() {
	logFormat()
}

func basicUsage() {
	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetFormatter(&logrus.TextFormatter{
		ForceColors:            false,
		FullTimestamp:          true,
		TimestampFormat:        time.DateTime,
		DisableSorting:         true,
		DisableLevelTruncation: true,
	})
	log := logrus.WithField("app", "study").WithField("server", "logrus")
	log = log.WithFields(logrus.Fields{"user": "talon", "ip": "client ip"})
	log.Errorf("异常")
	log.Warning("异常")
	log.Infof("异常")
	log.Debugf("异常")
}

func printColorInTerm() {
	fmt.Println("\033[30m黑色前景色\033[0m恢复正常")
	fmt.Println("\033[31m红色前景色\033[0m恢复正常")
	fmt.Println("\033[32m绿色前景色\033[0m恢复正常")
	fmt.Println("\033[33m黄色前景色\033[0m恢复正常")
	fmt.Println("\033[34m蓝色前景色\033[0m恢复正常")
	fmt.Println("\033[35m紫色前景色\033[0m恢复正常")
	fmt.Println("\033[36m青色前景色\033[0m恢复正常")
	fmt.Println("\033[37m灰色前景色\033[0m恢复正常")
	fmt.Println("\033[40m黑色背景色\033[0m恢复正常")
	fmt.Println("\033[41m红色背景色\033[0m恢复正常")
	fmt.Println("\033[42m绿色背景色\033[0m恢复正常")
	fmt.Println("\033[43m黄色背景色\033[0m恢复正常")
	fmt.Println("\033[44m蓝色背景色\033[0m恢复正常")
	fmt.Println("\033[45m紫色背景色\033[0m恢复正常")
	fmt.Println("\033[46m青色背景色\033[0m恢复正常")
	fmt.Println("\033[47m灰色背景色\033[0m恢复正常")
}

func writeLogInFile() {
	file, _ := os.OpenFile("./src/03_gin/12_log/logrus/1_basic/logger.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	logrus.SetOutput(io.MultiWriter(file, os.Stdout))
	logrus.Warnf("警告")
	logrus.Errorf("错误")

}

const (
	CBlack = iota
	CRed
	CGreen
	CYellow
	CBlue
	CPurple
	CCyan
	CGray
)

type MyFormatter struct {
	Prefix     string
	TimeFormat string
}

func (f MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	// 设置颜色
	var color int
	switch entry.Level {
	case logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel:
		color = CRed
	case logrus.WarnLevel:
		color = CYellow
	case logrus.InfoLevel:
		color = CGreen
	case logrus.DebugLevel:
		color = CBlue
	case logrus.TraceLevel:
		color = CGray
	default:
		color = CGreen
	}
	// 设置buffer缓冲区
	var b *bytes.Buffer
	if entry.Buffer == nil {
		b = &bytes.Buffer{}
	} else {
		b = entry.Buffer
	}
	// 文件的行号
	fileVal := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
	// 函数名
	// 设置格式
	fmt.Fprintf(b, "[%s]\033[3%dm[%s]\033[0m [%s] %s %s %s\n",
		f.Prefix,
		color, entry.Level,
		entry.Time.Format(f.TimeFormat),
		fileVal,
		entry.Caller.Function,
		entry.Message)
	return b.Bytes(), nil
}

func logFormat() {
	logrus.SetLevel(logrus.TraceLevel)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&MyFormatter{"GIN", time.DateTime})
	//logrus.Panicf("你好")
	//logrus.Fatalf("你好")
	logrus.Errorf("你好")
	logrus.Warnf("你好")
	logrus.Infof("你好")
	logrus.Debugf("你好")
	logrus.Tracef("你好")
}
